package com.lk.config;

import org.springframework.stereotype.Component;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;

/**
 * 从websocket中获取用户session
 * @author lk
 */
@Component
public class HttpSessionConfigurator extends Configurator
                                     implements ServletRequestListener {
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        // 在请求初始化时捕获HttpSession
        HttpSession session = ((HttpServletRequest) sre.getServletRequest()).getSession();
    }

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        // 从HandshakeRequest的HttpServletRequest中获取HttpSession
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        if (httpSession != null) {
            // 将 HttpSession 存储到 WebSocket 会话的用户属性中
            sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
        }
        super.modifyHandshake(sec, request, response);
    }

    @Override
    public void requestDestroyed(ServletRequestEvent arg0) {
        // 如果需要，进行清理操作
    }
}